package com.hzcx.app.simplechat.ui.friend;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.ui.friend.adapter.FriendLableInfoAdapter;
import com.hzcx.app.simplechat.ui.friend.bean.FriendBean;
import com.hzcx.app.simplechat.ui.friend.bean.FriendCityBean;
import com.hzcx.app.simplechat.ui.friend.bean.FriendLableInfoBean;
import com.hzcx.app.simplechat.ui.friend.contract.FriendLableInfoContract;
import com.hzcx.app.simplechat.ui.friend.event.FriendLableNameEvent;
import com.hzcx.app.simplechat.ui.friend.event.FriendLablePeopleEvent;
import com.hzcx.app.simplechat.ui.friend.event.FriendLableRefreshEvent;
import com.hzcx.app.simplechat.ui.friend.presenter.FriendLableInfoPresenter;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.view.MainBlueConfirmButton;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 新建标签页面
 */
public class FriendLableInfoActivity extends BaseActivity<FriendLableInfoPresenter> implements FriendLableInfoContract.View {

    public static final String INTENT_LABLE_ID = "INTENT_LABLE_ID";
    public static final String INTENT_IS_EDIT = "INTENT_IS_EDIT";

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.btn_commit)
    MainBlueConfirmButton btnCommit;
    @BindView(R.id.cons_toolbar)
    ConstraintLayout consToolbar;
    @BindView(R.id.rv_lable)
    RecyclerView rvLable;
    private List<FriendBean> listData;
    private FriendLableInfoAdapter lableInfoAdapter;
    private String id;
    private boolean isEdit = false;

    @Override
    public int getLayout() {
        return R.layout.activity_friend_lable_create;
    }

    @Override
    public void initPresenter() {
        mPresenter = new FriendLableInfoPresenter();
    }

    @Override
    public void initView() {

        btnCommit.setPadding(1, 1, 1, 1);// 让数字全部显示出来

        listData = new ArrayList<>();
        lableInfoAdapter = new FriendLableInfoAdapter(listData);
        rvLable.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvLable.setAdapter(lableInfoAdapter);
    }

    @Override
    public void initData() {
        id = getIntent().getStringExtra(INTENT_LABLE_ID);
        isEdit = getIntent().getBooleanExtra(INTENT_IS_EDIT, false);
        if (isEdit) {
            mPresenter.getFriendLableInfo(this, id);
        } else {
            addHeader();
        }


        lableInfoAdapter.setOnDeleteListener((headerPos, contentPos) -> {
            listData.get(headerPos - 1).getCity().remove(contentPos);
            lableInfoAdapter.notifyDataSetChanged();
        });
    }

    @OnClick({R.id.btn_commit})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.btn_commit:
                mPresenter.createFriendLable(this, listData, tv_lable_name.getText().toString(), id);
                break;
        }
    }

    /**
     * 添加头部
     */
    private TextView tv_lable_name, tv_add, tv_lable_num;

    private void addHeader() {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_friend_lable_info_header, null);
        tv_lable_name = view.findViewById(R.id.tv_lable_name);
        tv_add = view.findViewById(R.id.tv_add);
        tv_lable_num = view.findViewById(R.id.tv_lable_num);


        tv_lable_name.setOnClickListener(view1 -> startActivity(new Intent(FriendLableInfoActivity.this, FriendLableCreateNameActivity.class)
                .putExtra(FriendLableCreateNameActivity.INTENT_CONTENT, tv_lable_name.getText().toString().equals("未设置标签名字") ? null :
                        tv_lable_name.getText().toString())));

        tv_add.setOnClickListener(view12 -> {
            Intent intent = new Intent(FriendLableInfoActivity.this, FriendListByLableActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(FriendListByLableActivity.INTENT_LIST_BUNDLE, listData.toArray());
            intent.putExtras(bundle);
            startActivity(intent);
        });

        lableInfoAdapter.addHeaderView(view);
        lableInfoAdapter.notifyDataSetChanged();
    }

    /**
     * 修改标签名称
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateLableName(FriendLableNameEvent event) {
        tv_lable_name.setText(event.getName());
        checkData();
    }

    /**
     * 标签人员变动
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void peopleUpdate(FriendLablePeopleEvent event) {
        if (event.getFriendBeanList() != null && event.getFriendBeanList().size() > 0) {
            LogUtils.d(new Gson().toJson(event.getFriendBeanList()));
            listData.clear();
            listData.addAll(event.getFriendBeanList());
            lableInfoAdapter.notifyDataSetChanged();
        }
        setLableNum();
        checkData();
    }

    private void checkData() {
        if (tv_lable_name.getText().toString().equals("未设置标签名字")
                && listData.size() <= 0) {
            btnCommit.setBtnEnabled(false);
        } else {
            btnCommit.setBtnEnabled(true);
        }
    }

    /**
     * 创建或修改标签成功
     */
    @Override
    public void createSuccess() {
        showError("修改成功");
        EventBus.getDefault().post(new FriendLableRefreshEvent());
        finish();
    }

    /**
     * 标签详情获取成功
     *
     * @param data
     */
    @Override
    public void lableResult(FriendLableInfoBean data) {
        try {
            addHeader();
            listData.clear();
            listData.addAll(data.getMembers_data());
            lableInfoAdapter.notifyDataSetChanged();
            tv_lable_name.setText(data.getName());
            setLableNum();
            checkData();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取标签总人数
     */
    private void setLableNum() {
        int num = 0;
        for (FriendBean bean : listData) {
            if (listData == null || bean == null || bean.getCity() == null || bean.getCity().size() <= 0) {
                continue;
            }
            for (FriendCityBean subBean : bean.getCity()) {
                num++;
            }
        }
        tv_lable_num.setText("标签成员(" + num + ")");
    }
}
